#include <stdarg.h>
#include <stdlib.h>
#include "rstring.h"

void rstring_ref(rstring_t *self)
{
	if (self)
		self->ref++;
}

void rstring_unref(rstring_t *self)
{
	if (self && --(self->ref) == 0)
	{
		free(self->content);
		free(self);
	}
}

void rstring_release(rstring_t **self)
{
	if (self)
	{
		rstring_unref(*self);
		*self = NULL;
	}
}

rstring_t *rstring_new(void)
{
	rstring_t *self = malloc(sizeof(rstring_t));

	self->ref = 1;
	self->size = 16;
	self->length = 0;
	self->content = malloc(self->size + 1);
	self->content[0] = 0;
	return self;
}

rstring_t *rstring_new_char(char ch)
{
	rstring_t *self = malloc(sizeof(rstring_t));

	self->ref = 1;
	self->size = 16;
	self->length = 1;
	self->content = malloc(self->size + 1);
	self->content[1] = 0;
	self->content[0] = ch;
	return self;
}

rstring_t *rstring_new_string(const char *s)
{
	int len = (int)strlen(s);
	rstring_t *self = malloc(sizeof(rstring_t));

	self->ref = 1;
	self->size = len < 16 ? 16 : len;
	self->length = len;
	self->content = malloc(self->size + 1);
	self->content[len] = 0;
	memcpy(self->content, s, len);
	return self;
}

void rstring_append(rstring_t *self, char ch)
{
	if (self->length + 1 > self->size)
	{
		self->size *= 2;
		self->content = realloc(self->content, self->size + 1);
	}

	self->content[self->length] = ch;
	self->content[++self->length] = 0;
}

char rstring_is_one_of(rstring_t *self, int count, ...)
{
	va_list args;
	va_start(args, count);

	for (int i = 0; i < count; i++)
	{
		if (rstring_equals(self, va_arg(args, const char *)))
		{
			va_end(args);
			return 1;
		}
	}

	va_end(args);
	return 0;
}
